package com.shop.gateway.filters.factory;

import com.shop.gateway.config.AuthConfig;
import com.shop.gateway.util.AuthValid;
import com.shop.gateway.util.Validtors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/1/10
 */
@Component
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {

    @Autowired
    AuthConfig authConfig;

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            List<String> headers = request.getHeaders().get("AUTH");
            if (Validtors.urlValid.valid(request.getPath().value(), authConfig.getValidUrls()) && !CollectionUtils.isEmpty(headers)) {
                String token = headers.get(0);
                AuthValid<Integer,String> authValid = (a, params) -> 200;
                Integer validCode = authValid.valid(token);
                if (!validCode.equals(200)) {
                    exchange.getResponse().setStatusCode(HttpStatus.GATEWAY_TIMEOUT);
                    exchange.getResponse().getHeaders().add("validCode", validCode.toString());
                    return exchange.getResponse().setComplete();
                }
            }
            exchange.getResponse().getHeaders().add("validCode", "200");
            return chain.filter(exchange.mutate().request(request).build());
        };
    }
}
